package com.example.hello.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Component
public class FileUploadUtil {

    @Value("${file.upload.path:/upload}")
    private String uploadPath;

    @Value("${file.upload.url-prefix:/files}")
    private String urlPrefix;

    /**
     * 上传文件
     * @param file 文件
     * @param directory 子目录
     * @return 文件访问URL
     */
    public String uploadFile(MultipartFile file, String directory) throws Exception {
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("上传文件不能为空");
        }

        // 获取文件名并生成新文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFilename = UUID.randomUUID().toString().replace("-", "") + fileExtension;

        // 创建目录
        String dirPath = uploadPath + "/" + directory;
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 保存文件
        Path filePath = Paths.get(dirPath, newFilename);
        Files.write(filePath, file.getBytes());

        // 返回文件URL
        return urlPrefix + "/" + directory + "/" + newFilename;
    }

    /**
     * 删除文件
     * @param fileUrl 文件URL
     * @return 删除结果
     */
    public boolean deleteFile(String fileUrl) {
        if (fileUrl == null || fileUrl.isEmpty()) {
            return false;
        }

        // 从URL中提取文件路径
        String filePath = fileUrl.replace(urlPrefix, uploadPath);
        File file = new File(filePath);
        
        if (file.exists() && file.isFile()) {
            return file.delete();
        }
        
        return false;
    }
} 